<template>
  <div class="design-canvas">
    <div class="toolbar">
      <div class="tool-group">
        <el-tooltip content="选择工具" placement="bottom">
          <el-button :type="currentTool === 'select' ? 'primary' : ''" circle @click="setTool('select')">
            <el-icon><Pointer /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="矩形" placement="bottom">
          <el-button :type="currentTool === 'rectangle' ? 'primary' : ''" circle @click="setTool('rectangle')">
            <el-icon><CreditCard /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="圆形" placement="bottom">
          <el-button :type="currentTool === 'circle' ? 'primary' : ''" circle @click="setTool('circle')">
            <el-icon><Aim /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="文本" placement="bottom">
          <el-button :type="currentTool === 'text' ? 'primary' : ''" circle @click="setTool('text')">
            <el-icon><EditPen /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="图片" placement="bottom">
          <el-button :type="currentTool === 'image' ? 'primary' : ''" circle @click="setTool('image')">
            <el-icon><Picture /></el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <div class="tool-group">
        <el-tooltip content="撤销" placement="bottom">
          <el-button circle :disabled="!canUndo" @click="undo">
            <el-icon><Back /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="重做" placement="bottom">
          <el-button circle :disabled="!canRedo" @click="redo">
            <el-icon><Right /></el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <div class="tool-group">
        <el-tooltip content="保存" placement="bottom">
          <el-button type="success" circle @click="saveDesign">
            <el-icon><Check /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="预览" placement="bottom">
          <el-button type="info" circle @click="previewDesign">
            <el-icon><View /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <div class="canvas-container">
      <div class="canvas-wrapper">
        <div class="ai-assistant">
          <el-button type="primary" @click="showAiPanel = !showAiPanel">
            <el-icon><Magic /></el-icon>
            AI 辅助设计
          </el-button>
        </div>

        <div class="canvas" ref="canvasRef" @click="handleCanvasClick" @mousemove="handleMouseMove">
          <div
            v-for="element in elements"
            :key="element.id"
            :class="['canvas-element', { 'selected': selectedElement?.id === element.id }]"
            :style="getElementStyle(element)"
            @click.stop="selectElement(element)"
          >
            <template v-if="element.type === 'text'">
              {{ element.content }}
            </template>
            <template v-else-if="element.type === 'image'">
              <el-image :src="element.src" fit="contain" />
            </template>
          </div>

          <div v-if="isDragging" class="drag-preview" :style="dragPreviewStyle"></div>
        </div>
      </div>

      <transition name="slide">
        <div v-if="showAiPanel" class="ai-panel">
          <div class="panel-header">
            <h3>AI 辅助设计</h3>
            <el-button type="text" @click="showAiPanel = false">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>

          <div class="panel-content">
            <el-input
              v-model="aiPrompt"
              type="textarea"
              :rows="4"
              placeholder="请描述您想要实现的设计效果..."
            />

            <div class="ai-actions">
              <el-button type="primary" @click="generateDesign">生成设计</el-button>
              <el-button @click="improveDesign">改进当前设计</el-button>
            </div>

            <div class="ai-suggestions">
              <h4>设计建议</h4>
              <ul>
                <li>尝试保持简洁的设计风格，避免过多的元素干扰</li>
                <li>确保界面有足够的空白区域，提高可读性</li>
                <li>按照用户习惯安排常用操作和交互元素</li>
                <li>保持色彩一致性，使用协调的配色方案</li>
              </ul>
            </div>
          </div>
        </div>
      </transition>
    </div>

    <div class="properties-panel" v-if="selectedElement">
      <div class="panel-header">
        <h3>属性面板</h3>
        <el-button type="text" @click="deselectElement">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>

      <div class="panel-content">
        <el-form label-position="top">
          <el-form-item label="位置">
            <div class="position-inputs">
              <div class="position-input">
                <span>X</span>
                <el-input-number v-model="selectedElement.x" :min="0" :step="1" @change="updateElement" />
              </div>
              <div class="position-input">
                <span>Y</span>
                <el-input-number v-model="selectedElement.y" :min="0" :step="1" @change="updateElement" />
              </div>
            </div>
          </el-form-item>

          <el-form-item label="尺寸">
            <div class="position-inputs">
              <div class="position-input">
                <span>宽</span>
                <el-input-number v-model="selectedElement.width" :min="1" :step="1" @change="updateElement" />
              </div>
              <div class="position-input">
                <span>高</span>
                <el-input-number v-model="selectedElement.height" :min="1" :step="1" @change="updateElement" />
              </div>
            </div>
          </el-form-item>

          <template v-if="selectedElement.type === 'text'">
            <el-form-item label="文本内容">
              <el-input
                v-model="selectedElement.content"
                type="textarea"
                :rows="3"
                @change="updateElement"
              />
            </el-form-item>

            <el-form-item label="字体">
              <el-select v-model="selectedElement.fontFamily" @change="updateElement">
                <el-option label="默认" value="Arial, sans-serif" />
                <el-option label="宋体" value="SimSun, serif" />
                <el-option label="黑体" value="SimHei, sans-serif" />
                <el-option label="雅黑" value="Microsoft YaHei, sans-serif" />
              </el-select>
            </el-form-item>

            <el-form-item label="字号">
              <el-input-number v-model="selectedElement.fontSize" :min="8" :max="72" @change="updateElement" />
            </el-form-item>
          </template>

          <el-form-item label="背景颜色">
            <el-color-picker v-model="selectedElement.backgroundColor" @change="updateElement" />
          </el-form-item>

          <el-form-item label="边框颜色">
            <el-color-picker v-model="selectedElement.borderColor" @change="updateElement" />
          </el-form-item>

          <el-form-item label="边框宽度">
            <el-input-number v-model="selectedElement.borderWidth" :min="0" :max="10" @change="updateElement" />
          </el-form-item>

          <el-form-item label="边框圆角">
            <el-input-number v-model="selectedElement.borderRadius" :min="0" :max="50" @change="updateElement" />
          </el-form-item>
        </el-form>

        <div class="panel-actions">
          <el-button type="danger" @click="deleteElement">删除元素</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Pointer,
  CreditCard,
  Aim,
  EditPen,
  Picture,
  Back,
  Right,
  Check,
  View,
  Close,
} from '@element-plus/icons-vue'

// 当前项目ID
const projectId = ref(1)

// 画布相关
const canvasRef = ref(null)
const currentTool = ref('select')
const isDragging = ref(false)
const dragStart = ref({ x: 0, y: 0 })
const dragCurrent = ref({ x: 0, y: 0 })
const elements = ref([
  {
    id: 1,
    type: 'rectangle',
    x: 100,
    y: 100,
    width: 200,
    height: 150,
    backgroundColor: '#f0f0f0',
    borderColor: '#cccccc',
    borderWidth: 1,
    borderRadius: 4
  },
  {
    id: 2,
    type: 'text',
    x: 150,
    y: 120,
    width: 100,
    height: 40,
    content: '示例文本',
    fontFamily: 'Arial, sans-serif',
    fontSize: 16,
    backgroundColor: 'transparent',
    borderColor: 'transparent',
    borderWidth: 0,
    borderRadius: 0
  }
])
const selectedElement = ref(null)

// 历史记录
const history = ref([])
const historyIndex = ref(-1)
const canUndo = computed(() => historyIndex.value > 0)
const canRedo = computed(() => historyIndex.value < history.value.length - 1)

// AI 面板
const showAiPanel = ref(false)
const aiPrompt = ref('')

// 拖拽预览样式
const dragPreviewStyle = computed(() => {
  if (!isDragging.value) return {}

  const startX = Math.min(dragStart.value.x, dragCurrent.value.x)
  const startY = Math.min(dragStart.value.y, dragCurrent.value.y)
  const width = Math.abs(dragCurrent.value.x - dragStart.value.x)
  const height = Math.abs(dragCurrent.value.y - dragStart.value.y)

  return {
    left: `${startX}px`,
    top: `${startY}px`,
    width: `${width}px`,
    height: `${height}px`
  }
})

// 设置当前工具
const setTool = (tool) => {
  currentTool.value = tool
  if (tool !== 'select') {
    deselectElement()
  }
}

// 处理画布点击
const handleCanvasClick = (event) => {
  if (currentTool.value === 'select') {
    // 如果点击的是画布空白区域，则取消选择
    deselectElement()
    return
  }

  // 获取画布相对位置
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  // 创建新元素
  const newElement = {
    id: Date.now(),
    type: currentTool.value === 'text' ? 'text' : 'rectangle',
    x,
    y,
    width: 100,
    height: 50,
    backgroundColor: currentTool.value === 'text' ? 'transparent' : '#f0f0f0',
    borderColor: currentTool.value === 'text' ? 'transparent' : '#cccccc',
    borderWidth: currentTool.value === 'text' ? 0 : 1,
    borderRadius: currentTool.value === 'circle' ? 50 : 0
  }

  if (currentTool.value === 'text') {
    newElement.content = '点击编辑文本'
    newElement.fontFamily = 'Arial, sans-serif'
    newElement.fontSize = 16
  }

  addElement(newElement)
  selectElement(newElement)

  // 添加完元素后切换回选择工具
  currentTool.value = 'select'
}

// 处理鼠标移动
const handleMouseMove = (event) => {
  if (isDragging.value) {
    const rect = canvasRef.value.getBoundingClientRect()
    dragCurrent.value = {
      x: event.clientX - rect.left,
      y: event.clientY - rect.top
    }
  }
}

// 添加元素
const addElement = (element) => {
  // 保存历史记录
  saveHistoryState()

  elements.value.push(element)
}

// 选择元素
const selectElement = (element) => {
  selectedElement.value = JSON.parse(JSON.stringify(element))
}

// 取消选择
const deselectElement = () => {
  selectedElement.value = null
}

// 更新元素
const updateElement = () => {
  // 保存历史记录
  saveHistoryState()

  const index = elements.value.findIndex(e => e.id === selectedElement.value.id)
  if (index !== -1) {
    elements.value[index] = JSON.parse(JSON.stringify(selectedElement.value))
  }
}

// 删除元素
const deleteElement = () => {
  if (!selectedElement.value) return

  // 保存历史记录
  saveHistoryState()

  elements.value = elements.value.filter(e => e.id !== selectedElement.value.id)
  selectedElement.value = null
}

// 获取元素样式
const getElementStyle = (element) => {
  return {
    position: 'absolute',
    left: `${element.x}px`,
    top: `${element.y}px`,
    width: `${element.width}px`,
    height: `${element.height}px`,
    backgroundColor: element.backgroundColor || 'transparent',
    border: `${element.borderWidth}px solid ${element.borderColor || 'transparent'}`,
    borderRadius: `${element.borderRadius}px`,
    fontFamily: element.fontFamily || 'Arial, sans-serif',
    fontSize: element.fontSize ? `${element.fontSize}px` : 'inherit',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden'
  }
}

// 保存历史状态
const saveHistoryState = () => {
  // 删除当前状态之后的所有状态
  if (historyIndex.value < history.value.length - 1) {
    history.value = history.value.slice(0, historyIndex.value + 1)
  }

  // 添加当前状态
  history.value.push(JSON.stringify(elements.value))
  historyIndex.value = history.value.length - 1
}

// 撤销
const undo = () => {
  if (!canUndo.value) return

  historyIndex.value--
  elements.value = JSON.parse(history.value[historyIndex.value])
  deselectElement()
}

// 重做
const redo = () => {
  if (!canRedo.value) return

  historyIndex.value++
  elements.value = JSON.parse(history.value[historyIndex.value])
  deselectElement()
}

// 保存设计
const saveDesign = () => {
  // 在实际应用中，这里应该保存到服务器
  ElMessage.success('设计已保存')
}

// 预览设计
const previewDesign = () => {
  ElMessage.info('预览功能开发中')
}

// AI 生成设计
const generateDesign = () => {
  if (!aiPrompt.value) {
    ElMessage.warning('请输入设计描述')
    return
  }

  ElMessage.success('AI 正在生成设计，请稍候...')
  // 这里应该调用 AI 接口生成设计

  // 模拟 AI 生成结果
  setTimeout(() => {
    saveHistoryState()

    // 清空当前设计
    elements.value = []

    // 添加示例设计
    if (aiPrompt.value.includes('登录')) {
      // 登录页面示例
      elements.value = [
        {
          id: Date.now(),
          type: 'rectangle',
          x: 100,
          y: 50,
          width: 300,
          height: 350,
          backgroundColor: '#ffffff',
          borderColor: '#e0e0e0',
          borderWidth: 1,
          borderRadius: 8
        },
        {
          id: Date.now() + 1,
          type: 'text',
          x: 150,
          y: 80,
          width: 200,
          height: 40,
          content: '用户登录',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 24,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        },
        {
          id: Date.now() + 2,
          type: 'rectangle',
          x: 130,
          y: 150,
          width: 240,
          height: 40,
          backgroundColor: '#f5f5f5',
          borderColor: '#e0e0e0',
          borderWidth: 1,
          borderRadius: 4
        },
        {
          id: Date.now() + 3,
          type: 'rectangle',
          x: 130,
          y: 210,
          width: 240,
          height: 40,
          backgroundColor: '#f5f5f5',
          borderColor: '#e0e0e0',
          borderWidth: 1,
          borderRadius: 4
        },
        {
          id: Date.now() + 4,
          type: 'rectangle',
          x: 130,
          y: 280,
          width: 240,
          height: 40,
          backgroundColor: '#1890ff',
          borderColor: '#1890ff',
          borderWidth: 0,
          borderRadius: 4
        },
        {
          id: Date.now() + 5,
          type: 'text',
          x: 130,
          y: 130,
          width: 80,
          height: 20,
          content: '用户名',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 14,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        },
        {
          id: Date.now() + 6,
          type: 'text',
          x: 130,
          y: 190,
          width: 80,
          height: 20,
          content: '密码',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 14,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        },
        {
          id: Date.now() + 7,
          type: 'text',
          x: 230,
          y: 280,
          width: 40,
          height: 40,
          content: '登录',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 14,
          color: '#ffffff',
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        }
      ]
    } else {
      // 默认页面布局
      elements.value = [
        {
          id: Date.now(),
          type: 'rectangle',
          x: 0,
          y: 0,
          width: 800,
          height: 60,
          backgroundColor: '#ffffff',
          borderColor: '#e0e0e0',
          borderWidth: 0,
          borderBottomWidth: 1,
          borderRadius: 0
        },
        {
          id: Date.now() + 1,
          type: 'text',
          x: 20,
          y: 0,
          width: 200,
          height: 60,
          content: 'Logo',
          fontFamily: 'Arial, sans-serif',
          fontSize: 20,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        },
        {
          id: Date.now() + 2,
          type: 'rectangle',
          x: 0,
          y: 60,
          width: 200,
          height: 540,
          backgroundColor: '#fafafa',
          borderColor: '#e0e0e0',
          borderWidth: 0,
          borderRightWidth: 1,
          borderRadius: 0
        },
        {
          id: Date.now() + 3,
          type: 'text',
          x: 20,
          y: 100,
          width: 160,
          height: 40,
          content: '菜单项 1',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 14,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        },
        {
          id: Date.now() + 4,
          type: 'text',
          x: 20,
          y: 140,
          width: 160,
          height: 40,
          content: '菜单项 2',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 14,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        },
        {
          id: Date.now() + 5,
          type: 'text',
          x: 20,
          y: 180,
          width: 160,
          height: 40,
          content: '菜单项 3',
          fontFamily: 'Microsoft YaHei, sans-serif',
          fontSize: 14,
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          borderWidth: 0,
          borderRadius: 0
        }
      ]
    }

    ElMessage.success('AI 设计生成完成')
    showAiPanel.value = false
  }, 2000)
}

// 改进当前设计
const improveDesign = () => {
  if (elements.value.length === 0) {
    ElMessage.warning('请先创建设计')
    return
  }

  ElMessage.success('AI 正在改进设计，请稍候...')

  // 模拟 AI 改进设计
  setTimeout(() => {
    saveHistoryState()

    // 应用一些设计改进
    elements.value.forEach(element => {
      if (element.type === 'rectangle' && element.backgroundColor !== 'transparent') {
        // 改进矩形的视觉效果
        element.borderRadius = Math.min(element.borderRadius + 2, 8)

        // 微调颜色
        if (element.backgroundColor.startsWith('#f')) {
          element.backgroundColor = '#f8f8f8'
        }
      }

      // 改进文本排版
      if (element.type === 'text') {
        element.fontFamily = 'Microsoft YaHei, sans-serif'
      }
    })

    ElMessage.success('设计改进完成')
    showAiPanel.value = false
  }, 1500)
}

// 初始化
saveHistoryState() // 保存初始状态
</script>

<style scoped>
.design-canvas {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f0f2f5;
}

.toolbar {
  display: flex;
  padding: 12px 16px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  gap: 16px;
}

.tool-group {
  display: flex;
  gap: 8px;
  border-right: 1px solid #e0e0e0;
  padding-right: 16px;
  margin-right: 0;
}

.tool-group:last-child {
  border-right: none;
}

.canvas-container {
  flex: 1;
  display: flex;
  overflow: hidden;
  position: relative;
}

.canvas-wrapper {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 24px;
  position: relative;
}

.canvas {
  width: 800px;
  height: 600px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.canvas-element {
  position: absolute;
  cursor: move;
  user-select: none;
}

.selected {
  outline: 2px solid #1890ff;
}

.drag-preview {
  position: absolute;
  border: 1px dashed #1890ff;
  background-color: rgba(24, 144, 255, 0.1);
  pointer-events: none;
}

.properties-panel {
  width: 280px;
  background-color: #fff;
  border-left: 1px solid #e0e0e0;
  overflow-y: auto;
}

.ai-assistant {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 10;
}

.ai-panel {
  width: 320px;
  background-color: #fff;
  border-left: 1px solid #e0e0e0;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e0e0e0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.panel-content {
  padding: 16px;
}

.position-inputs {
  display: flex;
  gap: 12px;
}

.position-input {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.position-input span {
  font-size: 12px;
  color: #909399;
}

.panel-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.ai-actions {
  margin: 16px 0;
  display: flex;
  gap: 12px;
}

.ai-suggestions {
  margin-top: 24px;
  color: #606266;
}

.ai-suggestions h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
}

.ai-suggestions ul {
  margin: 0;
  padding-left: 16px;
}

.ai-suggestions li {
  margin-bottom: 8px;
  font-size: 13px;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateX(100%);
}
</style>
